/**
 * 
 */
package org.cnbi.web.controller.base;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.tools.generic.NumberTool;
import org.cnbi.entity.Kemu;
import org.cnbi.entity.Menu;
import org.cnbi.entity.SysLog;
import org.cnbi.utils.date.DateUtil;
import org.cnbi.utils.json.JsonUtil;
import org.cnbi.utils.pojo.SqlParamsBean;
import org.cnbi.utils.pojo.UtilDim;
import org.cnbi.utils.string.StringUtil;
import org.cnbi.utils.tools.ActionConstants;
import org.cnbi.utils.tools.Constants;
import org.cnbi.utils.tools.GlobalConstants;
import org.cnbi.utils.tools.MenuConstants;
import org.cnbi.utils.tools.StateConstants;
import org.cnbi.utils.tools.SymbolConstants;
import org.cnbi.web.utils.BrowserUtils;
import org.cnbi.web.utils.ContextHolderUtils;
import org.cnbi.web.utils.IpUtil;
import org.springframework.web.servlet.ModelAndView;




/**
 * Copyright © 2014中国经邦. All rights reserved.
 * @author 龚佳新
 * @date 2014年4月10日下午7:31:13
 * @cnbi-web
 * 公共的Controller基类
 */
public class BaseController extends ContextHolderUtils {
	
	private static final Log logger = LogFactory.getLog(BaseController.class);
	
	public static final NumberTool numTools = new NumberTool();
	/**
	 * 月度
	 */
	public static final String MONTH = "Month";
	/**
	 * 季度
	 */
	public static final String SEASON = "Season";
	/**
	 * 年度
	 */
	public static final String YEAR = "Year";
	
	protected String[] getDimHelpArr(String scode){
		return scode.split("\\"+SymbolConstants.UNDERLINE);
	}
	
	/**
	 * @return
	 */
	public Map<String, String> getSqlMap() {
		String key = ActionConstants.INIT+MenuConstants.INDICATOR;
		String [] subjects = {key+GlobalConstants.SUBJECT[0],key+GlobalConstants.SUBJECT[1]};
		Map<String,String> sqlMap = new HashMap<String,String>();
		for(String sus:subjects){
			String subjectScode = StringUtil.getAllNumber(sus);
			sqlMap.put(subjectScode, getSqlByKey(sus));
		}
		return sqlMap;
	}
	
	/**
	 * @param param
	 * @param condition
	 */
	protected void dimMapHandle(ModelAndView view,SqlParamsBean param, Menu menu) {
		Map<UtilDim, List<UtilDim>> dimMap = new LinkedHashMap<UtilDim, List<UtilDim>>();
		dimMap.put(new UtilDim(param.getCompany(),Constants.COMPANYNAME,Constants.COMPANY), getDimListByKey(StringUtil.toUpperCaseFirstOne(Constants.COMPANY)));
		String periodKey =StringUtil.toUpperCaseFirstOne(Constants.PERIOD);
		dimMap.put(new UtilDim(param.getYear(),"年份",StringUtil.toLowerCaseFirstOne(YEAR)),getDimListByKeyAndSpcode(periodKey, ""));
	//	List<UtilDim> yearList = getDimListByKeyAndSpcode("Period", "");//DateUtil.getYearList(3)
	//	System.out.println(JsonUtil.generateJson(yearList));
		String spcode = menu.getSpcode();
		if(menu.getScode().contains(MONTH) ||spcode.contains(MenuConstants.COMPOSE) ||spcode.contains("forcecast")||spcode.contains("db")){
			dimMap.put(new UtilDim(param.getMonth(),"月份",StringUtil.toLowerCaseFirstOne(MONTH)), DateUtil.getMonthList());
		}else if(menu.getScode().contains(SEASON)){
			dimMap.put(new UtilDim(param.getSeason(),"季度",StringUtil.toLowerCaseFirstOne(SEASON)), DateUtil.getSeasonList());
		}
		if(menu.getScode().indexOf(MenuConstants.TABLE) != -1){
			dimMap.put(new UtilDim(param.getUnit()+"",Constants.UNITNAME,Constants.UNIT), DateUtil.getUnitList());
		}
		if(spcode.contains(MenuConstants.COMPOSE)){
			if(menu.getScode().contains(MenuConstants.INDICATOR)){
				dimMap.put(new UtilDim(MenuConstants.INDICATOR,"指标",MenuConstants.INDICATOR),null);
			}else if(menu.getScode().contains(MenuConstants.KEMU)){
				dimMap.put(new UtilDim(MenuConstants.KEMU,"科目",MenuConstants.KEMU),null);
				List<UtilDim> dims = getDim();
				dimMap.put(new UtilDim(dims.get(0).getScode(),"度量","measure"), getDim());
			}
		}
		if(null != view){
			view.addObject("dimMap",dimMap);
			view.addObject("dimMapJson",JsonUtil.generateJson(dimMap));
		}
	}
	private List<UtilDim> getDim() {
		List<UtilDim> list = new ArrayList<UtilDim>();
		//科目主题
		@SuppressWarnings("unchecked")
		Map<String,String> map = (Map<String,String>) ContextHolderUtils.getServletContext().getAttribute(Constants.SUBJECT + GlobalConstants.SUBJECT_KEMU);
		Set<String> set = map.keySet();
		Iterator<String> iter = set.iterator();
		while(iter.hasNext()){
			String key = (String) iter.next();
			UtilDim dim = new UtilDim(key, map.get(key));
			list.add(dim);
		}
		return list;
	}

	/**
	 * @param response
	 * @return
	 */
	protected ModelAndView firstNavHandle(String scode,HttpServletResponse response) {
		ModelAndView view = new ModelAndView();
		commonHandle(scode,view, response);
		return view;
	}
	/**
	 * @param menu
	 * @param response
	 * @return
	 */
	protected ModelAndView secondNavHandle(Menu menu, HttpServletResponse response) {
		ModelAndView view = new ModelAndView();
		   String spcode = menu.getSpcode();
		   view.addObject("pageBean", menu);
		   logger.info("pageBean>>>>>>>>>>>>>"+menu);
		   setContentType(response, null);
		   setContext(view);
		   view.setViewName(spcode);
		   view.addObject("numTools", numTools);
		return view;
	}
	
	/**
	 * 获取日志对象
	 */
	protected SysLog getSysLog(String content, Short level, Short type) {
		HttpServletRequest request = ContextHolderUtils.getRequest();
		String broswer = BrowserUtils.checkBrowse(request);
		SysLog log = new SysLog();
		log.setContent(content);;
		log.setLevel(level);
		log.setType(type);;
		log.setBroswer(broswer);
		log.setOperateTime(DateUtil.getCurDate(DateUtil.defaultFormat));
		log.setUser(getCurrentUser().getUsername());
		log.setHostIp(IpUtil.getIpAddr(request));
		log.setHostName(request.getRemoteHost());
		return log;
	}
	/**
	 * 页面请求时公共调用的处理的方法
	 * @param scode
	 * @param view
	 * @param response
	 */
	protected void commonHandle(String scode,ModelAndView view,HttpServletResponse response){
	   ContextHolderUtils.setContext(view);
	   //setPageNav(new Menu(scode),view);
	   setPageListNav(scode, view);
	   setContentType(response, null);
	}
	
	public static  String getCurrentNav(HttpServletRequest request){
		String nav = (String)request.getSession().getAttribute(StateConstants.OLDURL);
		if(null == nav){
			nav =MenuConstants.DEFALUT+"/index"+Constants.FILTER;
		}
		return nav;
	}
	
	protected List<Menu> getMenuListBySpcode(String spcode) {
		List<Menu> list  =(List<Menu>)ContextHolderUtils.getMenuList();
		for(Menu menu :list){
			if(spcode.equals(menu.getScode())){
			}else{
			}
		}
		return list;
	}
	/**
	 * 当菜单 为list的时间调用的
	 * @param scode
	 * @param view
	 */
	protected void setPageListNav(String scode,ModelAndView view){
		Menu activeMenu = getActiveNavMenu();
		List<Menu> list  =(List<Menu>)ContextHolderUtils.getMenuList();
		List<Menu> navChildrenList = new ArrayList<Menu>();
		if(null == activeMenu || !activeMenu.getScode().equals(scode)){
			for(Menu menu :list){
				if(menu.getLevel() == 1){
					if(scode.equals(menu.getScode())){
						menu.setIsactive(1);
						activeMenu = menu;
						setActiveNavMenu(menu);
					}else{
						menu.setIsactive(0);
					}
				}
			}
		}
		for(Menu menu :list){
			if(scode.equals(menu.getSpcode())){
				navChildrenList.add(menu);
				//System.out.println(menu.getSname()+"========="+menu.getIsactive());
			}
		}
		view.addObject("secondLevelNavList", navChildrenList);//imageSubfix
		
		if(scode.equals(MenuConstants.DASH)){
			Map<Menu,List> map = (Map<Menu, List>)getServletContext().getAttribute("dashNavMap");
			  if(null == map){
			        map = new LinkedHashMap<Menu,List>();
				for(Menu menu :navChildrenList){
					List<Menu> lists = new ArrayList<Menu>();
					for(Menu menus:list){
						if(menus.getSpcode().equals(menu.getScode())){
							Menu ss = new Menu();
							ss = menus;
							ss.setLevel(2);
							ss.setSpcode(MenuConstants.DASH);
							lists.add(ss);
							
						}
					}
					map.put(menu, lists);
				}
				getServletContext().setAttribute("dashNavMap", map);
			  }
			  view.addObject("secondLevelNavList",map);//imageSubfix
		}
		view.addObject("navList", list);
		view.addObject("pageBean", activeMenu);
		view.setViewName("main");
	
		view.addObject("imageSubfix", ".png");
	}
	private void setActiveMenu(Menu tree,Menu bean){
		List<Menu> children = tree.getChildren();
		if(null != children){
			for(Menu menu :children){
				int isActive = menu.getIsactive();
				if(null == bean){
					if (isActive == 1){
						setSessionDatas(StateConstants.ISACTIVE+MenuConstants.MENU, menu);
					}else{
						setActiveMenu(menu, bean);
					}
				}else{
					if (bean.getScode().equals(menu.getScode())) {
						menu.setIsactive(1);
						setSessionDatas(StateConstants.ISACTIVE+MenuConstants.MENU, menu);
					}else if(isActive == 1){
							menu.setIsactive(0);
					}else {
						setActiveMenu(menu, bean);
					}
				}
			}
		}
	}
	/**
	 * 当菜单 为tree的时间调用的
	 * @param scode
	 * @param view
	 */
	protected void setPageNav(Menu menu,ModelAndView view){
		Menu activeMenu = getActiveNavMenu();
		Menu menuTree  =ContextHolderUtils.getMenuTree();
		if(null == activeMenu || !activeMenu.getScode().equals(menu.getScode()) || null!=menuTree.getChildren()){
			long a = System.currentTimeMillis();
			setActiveMenu(menuTree, menu);
			logger.info("递归菜单共用了【"+(System.currentTimeMillis()-a)+"】毫秒的时间");
			activeMenu = getActiveNavMenu();
		}
		view.addObject("menuTree", menuTree);
		view.addObject("pageBean", activeMenu);
		view.setViewName("main");
	}
	protected Menu getActiveNavMenu(){
		return (Menu)getSession().getAttribute(StateConstants.ISACTIVE+MenuConstants.MENU);
	}
	private void setActiveNavMenu(Menu menu){
		setSessionDatas(MenuConstants.MENU+StateConstants.ISACTIVE, menu);
	}
	
	public void setSessionDatas(String key,Object object){
		getSession().setAttribute(key, object);
	}
	
	
	public static String getAccountNameByScode(String scode){
		 Map<String,String> map = new HashMap<String, String>();
		 @SuppressWarnings("unchecked")
		List<Kemu> list = (List<Kemu>) getServletContext().getAttribute(MenuConstants.KEMU+StateConstants.LIST);
		 for (int i = 0; i < list.size(); i++) {
			 Kemu kemu = list.get(i);
			map.put(kemu.getScode(), kemu.getSname());
		}
		return map.get(scode);
	}
	
	public static String getMeasureNameByScode(String scode){
		Map<String,String> map = (Map<String,String>) ContextHolderUtils.getServletContext().getAttribute(Constants.SUBJECT + GlobalConstants.SUBJECT_KEMU);
		return map.get(scode);
	}
	/** 基于@ExceptionHandler异常处理  因为xml文件里忆经配了，所以这里就不用了*/
	/*@ExceptionHandler
	public String exp(HttpServletRequest request, Exception ex){
		request.setAttribute("ex", ex);
		// 根据不同错误转向不同页面
		if(ex instanceof BusinessException) {
			return "error";
		}else if(ex instanceof ParameterException) {
			return "error-parameter";
		} else {
			return "error";
		}
	}*/
}
